<?php

class User_Action_Signup extends Action
{
	function execute($request)
	{
		$form = Form::factory('user/signup');

		$config = Config::instance() -> read('user.signup');

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			try
			{
				$table = Model::getTable('user');

				$data = $form -> getData();

				$user = $table -> fetchNew();

				$user -> fromArray($data);

				$user -> created_at = time();

				$user -> created_ip = $request -> getClientIp();

				$user -> is_verified = !$config -> verify_email;

				$user -> is_approved = $config -> auto_approval;
				$user -> is_active = $config -> auto_active;
				$user -> role_id = $config -> get('level_id', 6);

				if ($config -> auto_password)
				{
					$password = Text::random(8);
				}
				else
				{
					$password = $data['password'];
				}

				if ($config -> require_username)
				{
					$user -> username = $data['username'];
				}
				else
				{
					$user -> username = Text::random(6);
				}

				$user -> setPassword($password);

				$user -> save();

				// break step 2
				if ($config -> welcome_email)
				{
					Mailer::factory('user.signup.welcome') -> send($user, $params = array(
						'user' => $user,
						'password' => $password
					));
				}

				if ($config -> auto_password)
				{
					Mailer::factory('user.signup.password') -> send($user, $params = array(
						'user' => $user,
						'password' => $password
					));
				}

				if ($config -> verify_email)
				{
					$table = Model::getTable('core/verification');

					$verify = $table -> fetchNew();

					$verify -> code = Text::random(32);

					$verify -> type = 'user.signup';

					$verify -> created_at = time();

					$verify -> user_id = (int)$user -> getId();

					$verify -> save();

					Mailer::factory('user.signup.autopassword') -> send($user, $params = array(
						'user' => $user,
						'password' => $password,
						'verify' => $verify,
					));
				}

				$url = Agilet::getUrl($config -> redirect_url);

				Response::redirect($url);
			}
			catch(Exception $e)
			{
				$form -> setNotice($e -> getMessage());
			}
		}

		$request -> response = View::render('user/html/signup', $data = array('form' => $form));
	}

}
